<template>
  <div>
    <van-nav-bar
      title="登录页面"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />

    <van-form @submit="onSubmit">
      <!-- 输入手机号，调起手机号键盘 -->
      <van-field
        v-model="mobile"
        name="mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对',
          },
        ]"
      />
      <!-- 输入任意文本 -->
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="登录中"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
//调用登录接口需要导入axios
import { getlogin } from "./user.js";
//导入token.js
import { saveToken } from "../../utils/token.js";
export default {
  name: "login",
  data() {
    return {
      mobile: "",
      code: "",
      isLoading: false,
    };
  },
  methods: {
    onSubmit(values) {
      console.log("submit", values);
      this.isLoading = true;
      //调用登录接口 axios 的 地址接口文件
      getlogin(values)
        .then((res) => {
          console.log(res);
          //登录成功 轻提示
          this.$toast.success("登录成功");
          //登录成功 保存token
          saveToken(res.data.data);
          // 跳转首页
          this.$router.push({ path: "/" });
        })
        .catch((err) => {
          //登录失败轻提示
          this.$toast.success("手机号或验证码输入错误登录失败");
        })
        .then(() => {
          this.isLoading = false;
        });
    },
  },
};
</script>

<style lang='less'>
.van-nav-bar {
  .van-nav-bar__content {
    background-color: #3b8af2;
    color: #fff;

    .van-nav-bar__arrow {
      color: #fff;
    }
    .van-nav-bar__text {
      color: #fff;
    }
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>